'use strict'

const _ = require('lodash')
const moment = require('moment')
const Env = use('Env')
const { Test,FaProduct,FaNews, FaManyStore,UserWantbuy,ExhibitorReceipt,FaExhibitor,User,SmsCode,UserExhibitor,UserNews,UserProduct } = require("../../Models")
const Database = use('Database')
const { ERR, E } = require('../../../../constants')
const { AliYunService } = require('../../Services')
const { CryptUtil } = require('../../Util')
class UserController {
  async sendSmsCode({ request, response, view }) {
    let { phone } = request.all()

    
    if (/^1\d{10}$/.test(phone)) {
      let user = await User.query().where('mobile',phone).first()
      console.log(user)
      if (!user) {
        user = await User.create({
          username:phone,
          nickname:phone,
          password:'7b936ac78d26e69626313b0e7d62951d',
          salt:'wnFqKf',
          realname:phone,
          mobile:phone,
          status:'normal'
        })
      }

      let smsCode = await SmsCode.query().where('phone',phone).first()

      if (!smsCode) {smsCode = new SmsCode()}
      let m2 = moment(),
          m1 = moment(new Date(smsCode.updatedAt)),
          diff = m2.diff(m1,'second')
  
      
      console.log(diff)
      
      if (isNaN(diff) || (diff>60)){
        let code = Math.floor(Math.random()*(9999-1000))+1000

        let smsResult = await AliYunService.sendSMS(phone, 'SMS_195305195', {
          code:code
        })
        smsCode.phone = phone
        smsCode.code = code
        smsCode.isChecked = 'n'
        await smsCode.save()
        response.json({
          error:0,
          message:phone + ' code has been sent'
        })
      } else {
        response.json(ERR.LESSTHANSIXTY)
      }
    } else {
      response.json(ERR.PHONE_ERROR)
    }

    
  }

  async login({ params, request, response }) {
    let { phone, code } = request.all()
    let smsCode = await SmsCode.query().where('phone',phone).where('isChecked','n').first()
    if (!smsCode) {
      response.json(ERR.PHONE_LOGIN_ERROR)
      return false
    }

    let m2 = moment(),
        m1 = moment(new Date(smsCode.updatedAt)),
        diff = m2.diff(m1,'second')

    if (isNaN(diff) || (diff>60)){
      response.json(ERR.PHONE_LOGIN_ERROR)
    } else {
      if (code.trim() !== smsCode.code) {
        response.json(ERR.PHONE_LOGIN_ERRORCODE)
      } else {
        smsCode.isChecked = 'y'
        await smsCode.save()

        let user = await User.query().where('mobile', phone).first()
        if (!user) {
          // 创建用户
          user = await User.create({
            phone: phone,
          })
          
        }
        response.json({
          token: CryptUtil.jwtEncode({ userID: user.id }),
          user
        })
      }
    }
    
    
  }
  async authTest({ params, request, response }) {
    
    response.json(request.user)
    
  }

  async getExhibitor({request, response, params}) { 
    let faExhibitor = await FaExhibitor.query().select(Database.raw(`id,nickname,name,concat('${E.attchmentPrefix}',logo) as logoUrl`)).fetch()
    faExhibitor = faExhibitor.toJSON()
    
    response.json(faExhibitor)
  }

  async getUserSelf({ request, response }) {

    let { userID } = request.all()
    let user = request.user
    userID = user.id
    user = await User.query().where('id', userID).first()

    response.json(user)
  }
  async likeProduct({ request, response, view }) {
    let { productID,userID } = request.all()
    let user = request.user
    userID = user.id
    let isLike = await UserProduct.query().where('userID', userID).where('productID', productID).first()
    if (isLike) {

      await UserProduct.query().where('userID', userID).where('productID', productID).delete()
      response.json({ error: 0, UserProduct: "DELETE", productID })
      
    } else {
      let userProduct = new UserProduct()
      userProduct.userID = userID
      userProduct.productID = productID
      await userProduct.save()
      let product = await FaProduct.query().where('id', productID).first()
      response.json({ error: 0, userProduct, product })
    }
  }
  async likeProductList({ request, response, view }) {
    
    let user = request.user,
        userID = user.id
    let list = await UserProduct.query().where('userID',userID).with('product').fetch()
    response.json(list)
  }
  async likeExhibitorList({ request, response, view }) {
    
    let user = request.user,
        userID = user.id
    let list = await UserExhibitor.query().where('userID',userID).with('exhibitor').fetch()
    response.json(list)
  }
  async likeExhibitor({ request, response, view }) {
    let { exhibitorID,userID } = request.all()
    let user = request.user
    userID = user.id
    let isLike = await UserExhibitor.query().where('userID', userID).where('exhibitorID', exhibitorID).first()
    if (isLike) {

      await UserExhibitor.query().where('userID', userID).where('exhibitorID', exhibitorID).delete()
      response.json({ error: 0, UserExhibitor: "DELETE", exhibitorID })
      
    } else {
      let userExhibitor = new UserExhibitor()
      userExhibitor.userID = userID
      userExhibitor.exhibitorID = exhibitorID
      await userExhibitor.save()
      let exhibitor = await FaExhibitor.query().where('id', exhibitorID).first()
      response.json({ error: 0, userExhibitor, exhibitor })
    }
  }
  async likeNewsList({ request, response, view }) {
    
    let user = request.user,
        userID = user.id
    let list = await UserNews.query().where('userID',userID).with('news').fetch()
    response.json(list)
  }
  async likeNews({ request, response, view }) {
    let { newsID,userID } = request.all()
    let user = request.user
    userID = user.id
    let isLike = await UserNews.query().where('userID', userID).where('newsID', newsID).first()
    if (isLike) {

      await UserNews.query().where('userID', userID).where('newsID', newsID).delete()
      response.json({ error: 0, UserNews: "DELETE", newsID })
      
    } else {
      let userNews = new UserNews()
      userNews.userID = userID
      userNews.newsID = newsID
      await userNews.save()
      let news = await FaNews.query().where('id', newsID).first()
      response.json({ error: 0, userNews, news })
    }
  }

  async receipt({request, response, params}) {
    
    let { exhibitorName,contactPerson,phone,isKeep,isKeepPrev,expectArea,remark = '',suggestion='' } = request.all()
    // let user = request.user,
    //     userID = user.id

    // let exhibitorReceipt = await ExhibitorReceipt.query().where('userID',userID).first()
    // if (!exhibitorReceipt) {
      if (remark==null) remark = ''

      if (suggestion==null) suggestion = ''
      
      let exhibitorReceipt = await ExhibitorReceipt.create({
        exhibitorName,contactPerson,phone,isKeep,isKeepPrev,expectArea,remark,suggestion
      })
    // } else {
    //   exhibitorReceipt.exhibitorName = exhibitorName
    //   exhibitorReceipt.contactPerson = contactPerson
    //   exhibitorReceipt.phone = phone
    //   exhibitorReceipt.isKeep = isKeep
    //   exhibitorReceipt.expectArea = expectArea
    //   exhibitorReceipt.remark = remark
    //   await exhibitorReceipt.save()
    // }
    
    response.json(exhibitorReceipt)
  }

  async wantbuy({request, response, params}) {
    
    let { exhibitorID,productID,quantity,wantPerson, wantCompany,wantPhone,type,description } = request.all()
    let user = request.user,
        userID = user.id

    let exhibitor = await FaExhibitor.query().where('id',exhibitorID).first(),
        product = null,
        productName = ''

    if (type==2) {
      product = await FaProduct.query().where('id',productID).first(),
      productName = product.name
    }

    let userWantbuy = await UserWantbuy.create({
      userID, 
      wantPerson,
      wantCompany,
      wantPhone,
      exhibitorID,productID,
      quantity,
      exhibitorName:exhibitor.name,
      productName,
      type,
      description
    })
    
    
    response.json(userWantbuy)
  }

  async wantbuyList({request, response, params}) {
    
    let user = request.user,
        userID = user.id

    let list = await UserWantbuy.query().where('userID',userID).with('product').with('exhibitor').fetch()
    
    response.json(list)
  }
  async getWantbuy({request, response, params}) {
    let { id } = request.all()
    let user = request.user,
        userID = user.id

    let vo = await UserWantbuy.query().where('id',id).with('product').with('exhibitor').first()
    response.json(vo)
  }
}
module.exports = UserController
